package org.jeecg.modules.demo.mytest.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.modules.demo.mytest.entity.MtProject;
import org.jeecg.modules.demo.mytest.entity.MtProjectDocument;
import org.jeecg.modules.demo.mytest.mapper.MtProjectDocumentMapper;
import org.jeecg.modules.demo.mytest.mapper.MtProjectMapper;
import org.jeecg.modules.demo.mytest.service.IMtProjectService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Objects;

/**
 * @Description: 项目表
 * @Author: thankgod7
 * @Date: 2023-07-28
 * @Version: V1.0
 */
@Service
public class MtProjectServiceImpl extends ServiceImpl<MtProjectMapper, MtProject> implements IMtProjectService {

    @Resource
    private MtProjectMapper mtProjectMapper;
    @Resource
    private MtProjectDocumentMapper mtProjectDocumentMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delMain(String id) {
        mtProjectDocumentMapper.deleteByMainId(id);
        mtProjectMapper.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delBatchMain(Collection<? extends Serializable> idList) {
        for (Serializable id : idList) {
            mtProjectDocumentMapper.deleteByMainId(id.toString());
            mtProjectMapper.deleteById(id);
        }
    }

    @Override
    public void reCount(String dataId) {
        MtProject project = this.getById(dataId);
        if (Objects.nonNull(project)) {
            List<MtProjectDocument> documents = mtProjectDocumentMapper.selectByMainId(dataId);
            int totalCopies = 0;
            int totalPages = 0;
            for (MtProjectDocument document : documents) {
                totalCopies += document.getCopies();
                totalPages += document.getPages();
            }
            project.setTotalCopies(totalCopies);
            project.setTotalPage(totalPages);
            this.updateById(project);
        }
    }

}
